import React from 'react';
import { DeleteOutlined, PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons';
import { ProTable as PProTable } from '@ant-design/pro-components';

import {
  type BizAlarmRuleInfo,
  rulesWarningListApi,
  rulesWarningDeleteApi,
  rulesWarningAddOrSaveApi,
  rulesWarningDetailApi,
} from '@/api/rulesWarning';
import type { OperationType } from '@/constants';
import {
  OperationTypeList,
  AlarmLevelEnum,
  AlarmTypeEnum,
  typeToValueEnum,
  getEnumItem,
} from '@/constants';
import { useRouter } from '@/hooks/useRouter';
import { TableLocalePresets } from '@/utils/tableUtils';

import type { ActionType, ProColumns } from '@ant-design/pro-components';
import WarningAddForm from './modules/add';
// 使用constants中定义的枚举和工具函数

/**
 * 告警规则管理页面组件
 * 提供告警规则的创建、编辑、删除等功能
 */
const RulesConfigWarning = () => {
  // 路由导航
  const { navigate } = useRouter();

  // 表格操作引用
  const actionRef = useRef<ActionType>(null);

  // 表单实例
  const [form] = AForm.useForm();

  // 抽屉状态管理
  const [drawerShow, setDrawerShow] = useState(false);
  const [drawerType, setDrawerType] = useState<OperationType>('ADD');
  const [currentRecord, setCurrentRecord] = useState<Partial<BizAlarmRuleInfo>>({});

  // 表格状态管理

  // 加载状态
  const [_loading, _setLoading] = useState(false);

  /**
   * 获取告警规则列表数据
   * @param params 查询参数
   * @returns 格式化的表格数据
   */
  const fetchData = async (params: Record<string, unknown>) => {
    try {
      // 处理分页参数
      const requestParams = {
        ...params,
        page: params.current,
        size: params.pageSize,
      };

      const res = await rulesWarningListApi(requestParams);

      if (res.success && res.data) {
        return {
          success: true,
          data: res.data.records ?? [],
          total: res.data.total ?? 0,
        };
      } else {
        window.$message.error(res.message || '获取告警规则列表失败');
        return {
          success: false,
          data: [],
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取告警规则列表失败:', error);
      window.$message.error('获取告警规则列表失败，请稍后重试');
      return {
        success: false,
        data: [],
        total: 0,
      };
    }
  };

  /**
   * 删除单个告警规则
   * @param record 告警规则记录
   */
  const handleDelete = async (record: BizAlarmRuleInfo) => {
    // 参数验证
    if (!record || !record.id) {
      window.$message.error('删除失败：告警规则ID不存在');
      return;
    }

    const ruleName = record.alarmRuleName || '未知规则';

    AModal.confirm({
      title: '确认删除',
      content: `确定要删除告警规则"${ruleName}"吗？删除后不可恢复。`,
      okText: '确定',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          const res = await rulesWarningDeleteApi({ id: String(record.id!) });
          if (res.success) {
            window.$message.success('告警规则删除成功');
            actionRef.current?.reload();
          } else {
            window.$message.error(res.message || '删除失败');
          }
        } catch (error) {
          console.error('删除告警规则失败:', error);
          window.$message.error('删除失败，请重试');
        }
      },
    });
  };

  // 批量删除功能已移除

  // 表格列定义
  const columns: ProColumns<BizAlarmRuleInfo>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      search: false,
    },
    {
      title: '规则名称',
      dataIndex: 'alarmRuleName',
      key: 'alarmRuleName',
      width: 160,
      search: true,
    },
    {
      title: '告警级别',
      dataIndex: 'level',
      key: 'level',
      width: 100,
      search: true,
      valueEnum: typeToValueEnum(AlarmLevelEnum),
      render: (_, record) => {
        const level = getEnumItem(AlarmLevelEnum, record.level);
        return <ABadge status={level?.status as any} text={level?.label || '未知'} />;
      },
    },
    {
      title: '告警类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      search: true,
      valueEnum: typeToValueEnum(AlarmTypeEnum),
      render: (_, record) => {
        const type = getEnumItem(AlarmTypeEnum, record.type);
        return <span>{type?.label || '未知'}</span>;
      },
    },
    {
      title: '规则描述',
      dataIndex: 'remark',
      key: 'remark',
      width: 200,
      search: false,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      search: false,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 180,
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <ASpace size="small">
          <AButton
            type="link"
            size="small"
            onClick={() => {
              if (!record.id) {
                window.$message.error('告警规则ID不存在，无法查看配置');
                return;
              }
              navigate(`/rules/config/warning/detail?id=${record.id}&ruleId=${record.ruleId}`);
            }}
          >
            配置
          </AButton>
          <AButton
            type="link"
            size="small"
            onClick={async () => {
              if (!record.id) {
                window.$message.error('告警规则ID不存在，无法编辑');
                return;
              }

              try {
                const res = await rulesWarningDetailApi({ id: record.id! });
                if (res.success && res.data) {
                  handleEdit({
                    ...record,
                    ...res.data,
                  });
                } else {
                  window.$message.error(res.message || '获取告警规则详情失败');
                }
              } catch (error) {
                console.error('获取告警规则详情失败:', error);
                window.$message.error('获取告警规则详情失败，请稍后重试');
              }
            }}
          >
            编辑
          </AButton>
          <AButton type="link" size="small" danger onClick={() => handleDelete(record)}>
            删除
          </AButton>
        </ASpace>
      ),
    },
  ];

  /**
   * 打开新增告警规则抽屉
   */
  const handleAdd = () => {
    setDrawerType('ADD');
    setCurrentRecord({});
    setDrawerShow(true);
  };

  /**
   * 关闭抽屉并重置状态
   */
  const handleDrawerClose = () => {
    setCurrentRecord({});
    setDrawerType('ADD');
    setDrawerShow(false);
    form.resetFields(); // 关闭时重置表单
  };

  /**
   * 打开编辑告警规则抽屉
   * @param record 告警规则记录
   */
  const handleEdit = (record: Partial<BizAlarmRuleInfo>) => {
    if (!record.id) {
      window.$message.error('告警规则ID不存在，无法编辑');
      return;
    }

    setCurrentRecord(record);
    setDrawerType('EDIT');
    setDrawerShow(true);

    // 预填充表单数据
    setTimeout(() => {
      form.setFieldsValue({
        ...record,
      });
    }, 100); // 延迟一点确保表单已渲染
  };

  /**
   * 处理表单提交
   */
  const handleSubmit = async () => {
    try {
      const params = await form.validateFields();
      const requestParams = {
        ...currentRecord,
        ...params,
      };

      const res = await rulesWarningAddOrSaveApi(requestParams);
      if (res.success) {
        form.resetFields();
        handleDrawerClose();
        const successMessage = drawerType === 'EDIT' ? '告警规则更新成功' : '告警规则创建成功';
        window.$message.success(successMessage);
        actionRef.current?.reload();
      } else {
        const errorMessage = drawerType === 'EDIT' ? '告警规则更新失败' : '告警规则创建失败';
        window.$message.error(res.message || errorMessage);
      }
    } catch (error) {
      console.error('提交失败:', error);
      if (error instanceof Error) {
        window.$message.error(`操作失败：${error.message}`);
      } else {
        window.$message.error('操作失败，请重试');
      }
    }
  };

  return (
    <div className="w-full">
      <ADrawer
        destroyOnHidden
        title={`告警规则${OperationTypeList[drawerType].label}`}
        width={600}
        closable={{ 'aria-label': 'Close Button' }}
        footer={
          <ARow justify="end">
            <ASpace>
              <AButton
                onClick={() => {
                  setDrawerShow(false);
                }}
              >
                返回
              </AButton>
              {drawerType != 'DETAIL' && (
                <AButton type="primary" onClick={handleSubmit}>
                  提交
                </AButton>
              )}
            </ASpace>
          </ARow>
        }
        onClose={handleDrawerClose}
        open={drawerShow}
      >
        <div className="w-full px-8 py-8">
          <AForm form={form} layout="vertical" labelAlign="right" labelCol={{ span: 12 }}>
            <React.Suspense fallback={<ASpin />}>
              <WarningAddForm
                form={form}
                data={currentRecord}
                mode={drawerType === 'EDIT' ? 'edit' : 'add'}
              />
            </React.Suspense>
          </AForm>
        </div>
      </ADrawer>
      <PProTable<BizAlarmRuleInfo>
        className="mh-table"
        actionRef={actionRef}
        columns={columns}
        request={fetchData}
        rowKey="id"
        search={{
          span: 6,
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
        }}
        scroll={{ x: 1000 }}
        size="small"
        options={{
          density: false,
          reloadIcon: (
            <AButton icon={<ReloadOutlined />} key="reload">
              刷新
            </AButton>
          ),
          setting: {
            draggable: true,
            checkable: true,
            showListItemOption: true,
            settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
            listsHeight: 400,
          },
        }}
        toolBarRender={() => [
          <AButton
            key="add"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              handleAdd();
              // 设置默认值
              setTimeout(() => {
                form.setFieldsValue({
                  level: 0, // 默认告警级别：普通
                  type: 1, // 默认告警类型：设备告警
                });
              }, 100);
            }}
          >
            新增告警规则
          </AButton>,
        ]}
        locale={TableLocalePresets.product(actionRef)}
      />
    </div>
  );
};

export default RulesConfigWarning;
